import { Prisma, PrismaClient } from "@prisma/client";
import timestamp from "time-stamp";
import express from "express";

const prisma = new PrismaClient({
  log: ["query", "info", "warn", "error"],
});
const router = express.Router();

router.get("/get", async function (req, res) {
  const { phoneNumber, type } = req.query;

  const phoneNumberAnd = phoneNumber
    ? {
        phoneNumber: String(phoneNumber),
      }
    : {};
  const typeAnd = type
    ? {
        type: String(type),
      }
    : {};

  const logs = await prisma.log.findMany({
    orderBy: {
      createTime: "desc",
    },
    where: {
      ...phoneNumberAnd,
      ...typeAnd,
    },
    take: 100,
  });
  return res.json({
    code: 0,
    data: logs,
  });
});
router.get("/getError", async function (req, res) {
  const logs = await prisma.$queryRaw(
    Prisma.sql`select
    *
from
    Log
where
    createTime in (
        select
            createTime
        from
            (
                select
                    phoneNumber,
                    max(createTime) as createTime
                from
                    Log
                group by
                    phoneNumber
            ) t
    )
    AND phoneNumber in (
        select
            phoneNumber
        from
            (
                select
                    phoneNumber,
                    max(createTime) as createTime
                from
                    Log
                group by
                    phoneNumber
            ) t
    )
    AND (
        battery < 15
        or TIMESTAMPDIFF(SECOND, createTime, now()) > (8 * 60 * 60 + 5 * 60)
    )
order by
    createTime desc;`
  );
  // const logs = await prisma.log.groupBy({
  //   by: ["phoneNumber"],
  //   _max: {
  //     createTime: true,
  //   },
  //   _min: {
  //     battery: true,
  //   },
  //   where: {
  //     OR: [
  //       {
  //         battery: {
  //           lt: 15,
  //         },
  //       },
  //       {
  //         AND: [
  //           {
  //             createTime: {
  //               lt: new Date(Date.now() - 5 * 60 * 1000).toISOString(),
  //             },
  //           },
  //         ],
  //       },
  //     ],
  //   },
  // });
  return res.json({
    code: 0,
    data: logs,
  });
});
router.post("/add", async function (req, res) {
  const { type, curApp, msg, phoneNumber, createTime, battery } = req.body;
  if (!phoneNumber) {
    return res.json({
      code: -1,
      msg: "phoneNumber必填",
    });
  }
  try {
    await prisma.log.create({
      data: {
        type,
        curApp,
        msg,
        createTime,
        battery,
        phoneNumber,
      },
    });
    return res.json({
      code: 0,
      data: [],
    });
  } catch (e) {
    return res.json({
      code: -1,
      msg: e,
    });
  }
});

export { router };
